package service

import (
	"context"
	"mall_2.0/pkg/utils/ctl"
	"mall_2.0/pkg/utils/log"
	"mall_2.0/respository/db/dao"
	"mall_2.0/respository/db/model"
	"mall_2.0/types"
	"sync"
)

var AddressSrvIns *AddressSrv
var AddressSrvOnce sync.Once

type AddressSrv struct{}

func GetAddressSrv() *AddressSrv {
	AddressSrvOnce.Do(func() {
		AddressSrvIns = &AddressSrv{}
	})
	return AddressSrvIns
}

// AddressCreate 创建地址
func (s *AddressSrv) AddressCreate(ctx context.Context, req *types.AddressCreateReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	addressDao := dao.NewAddressDao(ctx)
	address := &model.Address{
		UserID:  u.ID,
		Name:    req.Name,
		Phone:   req.Phone,
		Address: req.Address,
	}
	err = addressDao.CreateAddress(address)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}

// AddressShow 获取某个详细地址
func (s *AddressSrv) AddressShow(ctx context.Context, req *types.AddressGetReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	a, err := dao.NewAddressDao(ctx).GetAddressByAID(req.Id, u.ID)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	resp = &types.AddressResp{
		ID:        a.ID,
		UserID:    a.UserID,
		Name:      a.Name,
		Phone:     a.Phone,
		Address:   a.Address,
		CreatedAt: a.CreatedAt.Unix(),
	}
	return
}

// AddressList 获取地址列表
func (s *AddressSrv) AddressList(ctx context.Context, req *types.AddressListReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	resp, err = dao.NewAddressDao(ctx).ListAddressByUID(u.ID)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}

// AddressUpdate 更新地址
func (s *AddressSrv) AddressUpdate(ctx context.Context, req *types.AddressServiceReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	addressDao := dao.NewAddressDao(ctx)
	address := &model.Address{
		UserID:  u.ID,
		Name:    req.Name,
		Phone:   req.Phone,
		Address: req.Address,
	}
	err = addressDao.UpdateAddress(req.Id, address)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	var addresses []*types.AddressResp
	addresses, err = addressDao.ListAddressByUID(u.ID)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	resp = &types.DataListResp{
		Item:  addresses,
		Total: int64(len(addresses)),
	}
	return
}

// AddressDelete 删除地址
func (s *AddressSrv) AddressDelete(ctx context.Context, req *types.AddressDeleteReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	err = dao.NewAddressDao(ctx).DeleteAddress(req.Id, u.ID)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}
